#include "ptzcontrol.h"
#include "crytstring.h"


void PTZControl::sendRequest(const char* dir){
    // 创建请求对象

    KVQuery kvs;
    kvs.add("channelId","1");
    kvs.add("value",dir);
    kvs.add("speed","20");

    QString tmp = QString::fromStdString(kvs.toString());
    CryptString crytStr(tmp);
    qDebug() << "before crypt tmp:" << tmp << endl;

    QString  token = crytStr.generateMD5();
    kvs.add("token",token.toStdString());
    kvs.erase("secret");
    tmp =QString::fromStdString(kvs.toString());

    QUrl url("http://192.168.105.222/xsw/api/ptz/control?");
    url.setQuery(tmp);
    qDebug() << "query:" << tmp << endl;

    request.setUrl(url);
    qDebug()<<"url"<<url;
    // 发送GET请求
    QNetworkReply *reply = manager.get(request);

    qDebug()<<"request finised";
    // 连接完成信号
    QObject::connect(reply, &QNetworkReply::finished, [=]() {
        if (reply->error() == QNetworkReply::NoError) {
            // 读取响应数据
            QByteArray data = reply->readAll();
            qDebug() << "Response:" << data;
        } else {
            qDebug() << "Error:" << reply->errorString();
        }
        reply->deleteLater(); // 清理内存
    });
}

void PTZControl::directionClicked(int direction)
{
    switch (direction) {
    case 0:
        sendRequest("u");
        break;
    case 1:
        sendRequest("2");
        break;
    case 2:
        sendRequest("r");
        break;
    case 3:
        sendRequest("4");
        break;
    case 4:
        sendRequest("d");
        break;
    case 5:
        sendRequest("3");
        break;
    case 6:
        sendRequest("l");
        break;
    case 7:
        sendRequest("1");
        break;
    }
}

void PTZControl::directionReleased()
{
    sendRequest("s");
}

void PTZControl::centerButtonClicked()
{

}
